<template>
  <div class="flex-column">
    <div class="flex justify-between">
      <div class="flex-1 flex mb-10">
        <el-button
          v-if="permission.trendcontrast"
          :disabled="contrastData.length < 2"
          type="primary"
          icon="el-icon-magic-stick"
          @click="trendContrast"
        >{{ $t('TREND_CONTRAST') }}</el-button>
        <el-button
          v-if="permission.bulkexport"
          type="primary"
          :disabled="!contrastData.length"
          @click="$debounce(exportRecord, 'select')"
        >{{ $t('BULK_EXPORT') }}</el-button>
        <el-button
          v-if="permission.allexport"
          type="primary"
          @click="$debounce(exportRecord, 'all')"
        >{{ $t('EXPORT_ALL') }}</el-button>
      </div>
      <div class="text-right flex flex-wrap justify-end">
        <el-select
          v-model="bizType"
          size="mini"
          style="width: 130px"
          class="ml-10 mb-10"
          clearable
          :placeholder="$t('TEST_TYPE')"
        >
          <el-option
            v-for="(item, index) in testListType"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- 录入时间 -->
        <el-date-picker
          v-model="rangeDate"
          class="ml-10 mb-10"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          :start-placeholder="$t('START_TIME')"
          :end-placeholder="$t('END_TIME')"
          align="right"
          style="width: 300px"
        />
        <el-input
          v-model.trim="sherchData.keyword"
          class="ml-10 mb-10"
          clearable
          maxlength="32"
          style="width: 250px"
          :placeholder="$t('TEST_RECORD_PLACEHOLDER')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-select
          v-model="stationType"
          clearable
          style="width: 200px"
          class="ml-10 mb-10"
          :placeholder="$t('SELECT_STATION')"
          @change="selectedIds = []"
        >
          <el-option value="no" :label="$t('NOT_A_Z')" />
          <el-option value="a" :label="$t('TRANS_DIRECT_START')" />
          <el-option value="z" :label="$t('TRANS_DIRECT_END')" />
        </el-select>
        <!-- 全部区域 -->
        <region-cascader
          v-show="stationType === 'no' || stationType === ''"
          style="width: 280px"
          class="ml-10 mb-10"
          :multiple="true"
          :selected-ids="selectedIds"
          @change="stationChange"
        />
        <!-- 占位用 -->
        <div v-show="stationType === 'no' || stationType === ''" style="width: 280px" />
        <!-- A端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          style="width: 280px"
          class="ml-10 mb-10"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'A_END_STATION_NAME' : 'Z_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? aStationChange(val) : zStationChange(val)
            }
          "
        />
        <!-- Z端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          class="ml-10 mb-10"
          style="width: 280px"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'Z_END_STATION_NAME' : 'A_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? zStationChange(val) : aStationChange(val)
            }
          "
        />
        <el-button class="ml-10 mb-10" type="primary" @click="$debounce(search)">{{ $t('QUERY') }}</el-button>
      </div>
    </div>
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :options="{ seletion: true }"
      :operate-width="80"
      @operate="operate"
      @pageChange="pageChange"
      @selectionChange="selectionChange"
    />
    <!-- 测试曲线详情 -->
    <line-detail
      :row-data="rowData"
      :visible="lineDetailShow"
      @loadData="loadData"
      @close="close"
    />
    <!-- 趋势对比 -->
    <trend-contrast
      :contrast-data="contrastData"
      :visible="showContrast"
      @close="showContrast = false"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {
    changeDecimal,
    pickerOptionsClassMonth,
    downloadFile,
    getParentsById
  } from '@/utils/common'
  import exportApi from '@/api/oen/ExportApi'
  import LineDetail from './components/LineDetail'
  import TrendContrast from './components/TrendContrast'
  import otdrTestResult from '@/api/oen/OtdrTestResult'
  import TableView from '@/components/TableView'
  import RegionCascader from '@/components/RegionCascader'

  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    components: {
      LineDetail,
      TrendContrast,
      TableView,
      RegionCascader
    },
    provide() {
      return {
        functionName: 'record',
        parentVM: this
      }
    },
    data() {
      const _this = this
      return {
        stationType: '',
        sherchData: {
          keyword: '',
          startStationIdList: [],
          endStationIdList: [],
          stationIdList: []
        },
        selectedIds: [],
        segmentId: '',
        device: '',
        cableName: '',
        portName: '',
        showContrast: false,
        lineDetailShow: false,
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        tableData: [],
        rowData: {},
        contrastData: [],
        changeDecimal: changeDecimal,
        rangeDate: null,
        pickerOptions: pickerOptionsClassMonth(this),
        tableHeader: [
          {
            label: 'TEST_NAME',
            prop: 'taskName',
            width: 120
          },
          {
            label: 'TEST_TYPE',
            prop: 'bizTypeName',
            width: 120
          },
          {
            label: 'SERVICE_NAME',
            prop: 'bizName',
            width: 120
          },
          {
            label: 'A_END_REGION_STATION',
            prop: 'startReginName',
            width: 180,
            formatter(row) {
              const parents = getParentsById(_this.stationTree, row.startReginId, 'regionId') || []
              return parents.reverse().map(i => i.regionName).join('/')
            }
          },
          {
            label: 'ANODE',
            prop: 'startDeviceName',
            width: 140,
            configType: 'extend'
          },
          {
            label: 'Z_END_REGION_STATION',
            prop: 'endReginName',
            width: 180,
            formatter(row) {
              const parents = getParentsById(_this.stationTree, row.endReginId, 'regionId') || []
              return parents.reverse().map(i => i.regionName).join('/')
            }
          },
          {
            label: 'ZNODE',
            prop: 'endDeviceName',
            width: 140,
            configType: 'extend'
          },
          {
            label: 'TESTING_DIRECTION',
            prop: 'testDirection',
            width: 120,
            configType: 'extend',
            formatter(row) {
              return row.testDirection ? _this.$t(row.testDirection + '_END') : ''
            }
          },
          {
            label: 'DEVICE_NAME',
            prop: 'deviceName',
            width: 140,
            configType: 'default'
          },
          {
            label: 'DEVICE_CODE',
            prop: 'deviceId',
            width: 140,
            configType: 'extend'
          },
          {
            label: 'LIGHTING_PORT',
            prop: 'portName',
            width: 100,
            configType: 'default'
          },
          {
            label: 'CABLE_NAME',
            prop: 'cableName',
            width: 200
          },
          {
            label: 'FIBER_NAME',
            prop: 'fiberName',
            width: 100
          },
          {
            label: 'LINK_SEGMENT_NAME',
            prop: 'linkSegmentName',
            width: 140
          },
          {
            label: 'CONN_EQUIPMENT',
            prop: 'connDeviceName',
            width: 120,
            configType: 'extend'
          },
          {
            label: 'CONN_PORT',
            prop: 'connPortName',
            width: 100,
            configType: 'extend'
          },
          {
            label: 'TEST_TIME',
            prop: 'startTime',
            width: 160
          },
          {
            label: 'EVENTS_NUMBER',
            prop: 'eventNum',
            width: 100,
            configType: 'extend'
          },
          {
            label: 'CABLE_LENGTH',
            prop: 'fiberLength',
            width: 130,
            formatter(row) {
              return _this.changeDecimal(row.fiberLength / 1000, 3, true)
            }
          },
          {
            label: 'LINK_LOSS',
            prop: 'totalLoss',
            width: 130,
            formatter(row) {
              return !row.totalLoss || row.totalLoss > 990000
                ? '--'
                : _this.changeDecimal(row.totalLoss, 3)
            },
            tips: 'LINK_LOSS_TIPS'
          },
          {
            label: 'TOTAL_RETURN_LOSS',
            prop: 'totalReturnLoss',
            width: 110,
            formatter(row) {
              return _this.changeDecimal(row.totalReturnLoss, 3)
            },
            tips: 'TOTAL_RETURN_LOSS_TIPS'
          },
          {
            label: 'AVERAGE_LOSS',
            prop: 'avgLoss',
            width: 150,
            formatter(row) {
              return row.avgLoss > 990000
                ? '--'
                : _this.changeDecimal(row.avgLoss, 3)
            },
            tips: 'AVERAGE_LOSS_TIPS'
          },
          {
            label: 'TEST_MODE',
            prop: 'testType',
            width: 120,
            formatter(row) {
              return _this.getTestType(row.testParam.testMode)
            }
          },
          {
            label: 'REFERENCE_CURVE',
            prop: 'isRefCurve',
            width: 120,
            formatter(row) {
              return row.isRefCurve ? _this.$t('OK_YES') : _this.$t('OK_NO')
            }
          }
        ],
        warningMsg: null,
        bizType: '',
        functionName: 'record'
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'baseRegionList', 'dictList', 'stationTree']),
      permission() {
        return this.$store.getters.getAuthData('link:record')
      },
      testListType() {
        const types = ['LINK_DETECT', 'TIME_DETECT', 'FAULT_LOCATION', 'BIZ_DETECT', 'BIZ_THROUGH']
        return this.dictList.BUSINESS_TYPES.filter(i => types.includes(i.value))
      }
    },
    watch: {
      'pageData.page': function() {
        this.contrastData = []
      }
    },
    activated() {
      this.loadData()
    },
    methods: {
      loadData() {
        const data = {
          ...this.pageData,
          ...searchData
        }
        otdrTestResult.queryPage(data).then(res => {
          this.tableData = res.list || []
          this.tableData.forEach((i, index) => {
            i.orderIndex = index + 1
            i.bizTypeName = i.bizType ? this.dictMap.BUSINESS_TYPES[i.bizType] : i.bizTypeName
            i.btns = [
              {
                key: 'view',
                label: 'DETAILS'
              }
            ]
          })
          this.pageData.total = res.total
        })
      },
      // 获取区域/站点/机房
      getRegionName(regionId) {
        const stationData = this.baseRegionList.find(i => i.regionId === regionId)
        return stationData ? stationData.regionName : ''
      },
      selectionChange(val) {
        this.contrastData = val
      },
      // 趋势对比
      trendContrast() {
        if (this.contrastData.length > 4) {
          this.warningMsg && this.warningMsg.close()
          this.warningMsg = null
          this.warningMsg = this.$message.error(this.$t('ONLY_4DATA_MOST'))
          return
        }
        this.showContrast = true
      },
      // 测试类型
      getTestType(type) {
        return this.dictMap.OTDR_TEST_MODE[type]
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        searchData = {
          ...this.getQueryData()
        }
        this.loadData()
      },
      // 曲线详情
      operate(data) {
        this.rowData = data.data
        this.lineDetailShow = true
      },
      close(load) {
        this.lineDetailShow = false
        if (load === true) {
          this.loadData()
        }
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      },
      getQueryData() {
        const timeData = this.rangeDate
          ? { startTime: this.rangeDate[0], endTime: this.rangeDate[1] }
          : {}
        const queryData = {
          ...timeData,
          bizType: this.bizType,
          ...this.sherchData
        }
        delete queryData.total
        return queryData
      },
      exportRecord(type) {
        let queryData = { taskIdList: ' ', type: 'all' }
        if (type !== 'all') {
          queryData.type = ''
          queryData.taskIdList = this.contrastData.map(i => i.taskId).join()
          this.exportFile(queryData)
        } else {
          queryData = this.getQueryData()
          this.$confirm(this.$t('EXPORT_ALL_TIPS', { count: 10000 }), this.$t('EXPORT_ALL'), {
            type: 'warning'
          }).then(res => {
            this.exportFile(queryData)
          })
        }
      },
      exportFile(queryData) {
        exportApi.otdrTestResult(queryData).then(res => {
          downloadFile(res, this.$t('MENU_TEST_RECORD'))
        })
      },
      // 区域搜索条件改变
      aStationChange(data) {
        this.sherchData.startStationIdList = data
      },
      zStationChange(data) {
        this.sherchData.endStationIdList = data
      },
      stationChange(data) {
        this.sherchData.stationIdList = data
      },
      getStr(str) {
        return str
          .trim()
          .replace(/\\/g, '\\\\') // 特殊字符转义
          .replace(/%/g, '\\%')
          .replace(/_/g, '\\_')
      }
    }
  }
</script>

<style scoped>
  .icon-AFSshaixuan {
    color: #c0c4cc;
    font-size: 20px;
  }
</style>
